package com.ssy.lingxi.product.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.product.CommodityStatusEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.MemberAndRoleIdDTO;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.product.api.model.request.SimpleIdRequest;
import com.ssy.lingxi.product.api.model.request.channelCommodity.*;
import com.ssy.lingxi.product.api.model.request.commodity.CommodityDetailRequest;
import com.ssy.lingxi.product.api.model.request.commodity.LogisticsRequest;
import com.ssy.lingxi.product.api.model.request.commodity.ShopRequest;
import com.ssy.lingxi.product.api.model.request.feign.CommodityNameRequest;
import com.ssy.lingxi.product.api.model.request.feign.CommodityPriceRequest;
import com.ssy.lingxi.product.api.model.response.channelCommodity.ChannelCommodityESResponse;
import com.ssy.lingxi.product.api.model.response.commodity.*;
import com.ssy.lingxi.product.api.model.response.feign.CommodityPriceResponse;
import com.ssy.lingxi.product.entity.Brand;
import com.ssy.lingxi.product.entity.Goods;
import com.ssy.lingxi.product.entity.channelCommodity.*;
import com.ssy.lingxi.product.entity.commodity.Commodity;
import com.ssy.lingxi.product.entity.customer.CustomerAttribute;
import com.ssy.lingxi.product.entity.customer.CustomerAttributeValue;
import com.ssy.lingxi.product.entity.customer.CustomerCategory;
import com.ssy.lingxi.product.entity.platform.Category;
import com.ssy.lingxi.product.repository.GoodsRepository;
import com.ssy.lingxi.product.repository.channelCommodity.*;
import com.ssy.lingxi.product.repository.commodity.CommodityRepository;
import com.ssy.lingxi.product.repository.customer.CustomerAttributeRepository;
import com.ssy.lingxi.product.repository.customer.CustomerAttributeValueRepository;
import com.ssy.lingxi.product.service.IChannelCommodityService;
import com.ssy.lingxi.product.service.es.ISyncEsCommodityService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class ChannelCommodityServiceImpl implements IChannelCommodityService {

    @Autowired
    private CommodityRepository commodityRepository;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ChannelCommodityRepository channelCommodityRepository;

    @Autowired
    private CustomerAttributeRepository customerAttributeRepository;

    @Autowired
    private CustomerAttributeValueRepository customerAttributeValueRepository;

    @Autowired
    private ChannelCommodityUnitPriceAndPicRepository channelCommodityUnitPriceAndPicRepository;

    @Autowired
    private ChannelCommodityMemberRepository channelCommodityMemberRepository;

    @Autowired
    private ChannelCommodityShopRepository channelCommodityShopRepository;

    @Autowired
    private ChannelCommodityAttributeRepository channelCommodityAttributeRepository;

    @Resource
    private ISyncEsCommodityService syncEsCommodityService;

    @Autowired
    private IRedisStringUtils redisStringUtils;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询渠道会员商品列表
     * @param pageVO
     * @param channelCommodityQueryRequest
     */
    @Override
    public Page<ChannelCommodityMember> getChannelCommodityMemberList(PageVO pageVO, ChannelCommodityQueryRequest channelCommodityQueryRequest){
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return channelCommodityMemberRepository.findAll(getSpecification(channelCommodityQueryRequest), page);
    }

    /**
     * 查询渠道商品列表
     * @param pageVO
     * @param channelCommodityQueryRequest
     */
    @Override
    public Page<ChannelCommodity> getChannelCommodityList(PageVO pageVO, ChannelCommodityQueryRequest channelCommodityQueryRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return channelCommodityRepository.findAll(getChannelCommoditySpecification(channelCommodityQueryRequest), page);
    }

    /**
     * 查询渠道会员商品
     * @param id
     */
    @Override
    public ChannelCommodityMember getChannelCommodityMember(Long id){
        return channelCommodityMemberRepository.findById(id).orElse(null);
    }

    /**
     * 查询渠道商品
     * @param id
     */
    @Override
    public ChannelCommodity getChannelCommodityById(Long id) {
        return channelCommodityRepository.findById(id).orElse(null);
    }

    /**
     * 添加渠道商品
     * @param sysUser
     * @param channelCommodityRequest
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public Long saveChannelCommodity(UserLoginCacheDTO sysUser, ChannelCommodityRequest channelCommodityRequest){
        Integer source = channelCommodityRequest.getSource();
        ChannelCommodity channelCommodity = new ChannelCommodity();
        Long commodityId = channelCommodityRequest.getCommodityId();
        LogisticsRequest logistics = channelCommodityRequest.getLogistics();
        if(commodityId != null && commodityId > 0){
            //复制
            BeanUtil.copyProperties(channelCommodityRequest, channelCommodity);
            //判断商品状态
            Integer status;
            //验证数据库中是否存在该商品数据
            if(source == 1){
                ChannelCommodityMember channelCommodityMember = channelCommodityMemberRepository.findById(commodityId).orElse(null);
                if(channelCommodityMember == null){
                    throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_NOT_EXIST);
                }
                status = channelCommodityMember.getStatus();
                if(!CommodityStatusEnum.On_Shelf.getCode().equals(status)){
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
                }
                channelCommodity.setCommodity(channelCommodityMember.getChannelCommodity().getCommodity());
                channelCommodity.setParentChannelCommodityMember(channelCommodityMember);
            }else{
                Commodity commodity = commodityRepository.findById(commodityId).orElse(null);
                if(commodity == null){
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
                status = commodity.getStatus();
                if(!CommodityStatusEnum.Pass.getCode().equals(status) && !CommodityStatusEnum.On_Shelf.getCode().equals(status) && !CommodityStatusEnum.Off_Shelf.getCode().equals(status)){
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
                }
                channelCommodity.setCommodity(commodity);
            }

            //是否允许使用会员折扣价购买
            Boolean isMemberPrice = channelCommodityRequest.getIsMemberPrice();
            List<ChannelUnitPriceAndPicRequest> unitPriceAndPicList = channelCommodityRequest.getUnitPriceAndPicList();

            //计算商品的最大值和最小值
            Double min = 0d;
            Double max = 0d;
            List<Map<String, Double>> collect = unitPriceAndPicList.stream().filter(commodityUnitPriceAndPic -> commodityUnitPriceAndPic != null && commodityUnitPriceAndPic.getUnitPrice() != null && commodityUnitPriceAndPic.getUnitPrice().size() > 0).map(ChannelUnitPriceAndPicRequest::getUnitPrice).collect(Collectors.toList());
            if(!collect.isEmpty()){
                min = Collections.min(collect.stream().map(m -> Collections.min(m.values())).collect(Collectors.toList()));
                max = Collections.max(collect.stream().map(m -> Collections.max(m.values())).collect(Collectors.toList()));
            }

            //判断是否所有渠道会员
            List<ChannelCommodityMember> channelCommodityMemberList = new ArrayList<>();
            Boolean isAllMember = channelCommodityRequest.getIsAllMember();
            if(isAllMember != null && isAllMember){
                ChannelCommodityMember commodityMember = new ChannelCommodityMember();
                commodityMember.setMemberId(0L);
                commodityMember.setMemberName("所有渠道");
                commodityMember.setMemberRoleId(channelCommodityRequest.getChildMemberRoleId());
                commodityMember.setMemberRoleName(channelCommodityRequest.getChildMemberRoleName());
                commodityMember.setIsMemberPrice(isMemberPrice);
                commodityMember.setUnitPriceAndPicList(this.getPrice(sysUser, unitPriceAndPicList, commodityMember));
                commodityMember.setStatus(CommodityStatusEnum.NEVER_Shelf.getCode());
                commodityMember.setMin(min);
                commodityMember.setMax(max);
                commodityMember.setChannelCommodity(channelCommodity);
                commodityMember.setLogistics(logistics);
                channelCommodityMemberList.add(commodityMember);
            }else{
                //遍历渠道会员
                List<ChannelCommodityMemberRequest> commodityMemberList = channelCommodityRequest.getCommodityMemberList();
                if(commodityMemberList != null && !commodityMemberList.isEmpty()){
                    Double finalMin = min;
                    Double finalMax = max;
                    commodityMemberList.forEach(commodityMemberRequest -> {
                        ChannelCommodityMember commodityMember = new ChannelCommodityMember();
                        commodityMember.setMemberId(commodityMemberRequest.getMemberId());
                        commodityMember.setMemberName(commodityMemberRequest.getMemberName());
                        commodityMember.setMemberTypeName(commodityMemberRequest.getMemberTypeName());
                        commodityMember.setMemberRoleId(channelCommodityRequest.getChildMemberRoleId());
                        commodityMember.setMemberRoleName(channelCommodityRequest.getChildMemberRoleName());
                        commodityMember.setIsMemberPrice(isMemberPrice);
                        commodityMember.setUnitPriceAndPicList(this.getPrice(sysUser, unitPriceAndPicList, commodityMember));
                        commodityMember.setStatus(CommodityStatusEnum.NEVER_Shelf.getCode());
                        commodityMember.setMin(finalMin);
                        commodityMember.setMax(finalMax);
                        commodityMember.setChannelCommodity(channelCommodity);
                        commodityMember.setLogistics(logistics);
                        channelCommodityMemberList.add(commodityMember);
                    });
                }
            }
            channelCommodity.setMemberList(channelCommodityMemberList);

            //设置会员信息
            channelCommodity.setMemberId(sysUser.getMemberId());
            channelCommodity.setMemberName(sysUser.getCompany());
            channelCommodity.setMemberRoleId(sysUser.getMemberRoleId());
            channelCommodity.setMemberRoleName(sysUser.getMemberRoleName());
            channelCommodity.setUserId(sysUser.getUserId());
            channelCommodity.setUserName(sysUser.getUserName());

            channelCommodityRepository.save(channelCommodity);
            return channelCommodity.getId();
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
    }

    /**
     * 批量获取商品价格
     * @param commoditySkuIdList
     * @return
     */
    @Override
    public Map<Long, Map<String, Double>> getCommodityPriceBatch(List<Long> commoditySkuIdList) {
        List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = channelCommodityUnitPriceAndPicRepository.findAllById(commoditySkuIdList);
        return commodityUnitPriceAndPicList.stream().collect(Collectors.toMap(ChannelCommodityUnitPricePic::getId, ChannelCommodityUnitPricePic::getUnitPrice));
    }

    /**
     * 批量查询商品价格和是否允许使用会员权益
     * @return
     */
    @Override
    public Map<Long, CommodityPriceResponse> getCommodityPriceAndMemberPriceBatch(List<Long> commoditySkuIdList) {
        Map<Long, CommodityPriceResponse> result = new HashMap<>();
        List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = channelCommodityUnitPriceAndPicRepository.findAllById(commoditySkuIdList);
        commodityUnitPriceAndPicList.forEach(channelCommodityUnitPricePic -> {
            CommodityPriceResponse commodityPriceResponse = new CommodityPriceResponse();
            commodityPriceResponse.setIsMemberPrice(channelCommodityUnitPricePic.getChannelCommodityMember().getIsMemberPrice());
            commodityPriceResponse.setCommodityPrice(channelCommodityUnitPricePic.getUnitPrice());
            result.put(channelCommodityUnitPricePic.getId(), commodityPriceResponse);
        });
        return result;
    }

    /**
     * 生成价格
     * @param sysUser
     * @param unitPriceAndPicList
     * @param commodityMember
     * @return
     */
    private List<ChannelCommodityUnitPricePic> getPrice(UserLoginCacheDTO sysUser, List<ChannelUnitPriceAndPicRequest> unitPriceAndPicList, ChannelCommodityMember commodityMember){
        //转换单价和图片
        List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = new ArrayList<>();
        unitPriceAndPicList.forEach(unitPriceAndPicRequest -> {
            ChannelCommodityUnitPricePic commodityUnitPriceAndPic = new ChannelCommodityUnitPricePic();

            //检查货品
            SimpleIdRequest goodsRequest = unitPriceAndPicRequest.getGoods();
            if(goodsRequest != null){
                Long goodsId = goodsRequest.getId();
                if(goodsId != null && goodsId > 0){
                    Goods goods = goodsRepository.findById(goodsId).orElse(null);
                    if(goods != null){
                        commodityUnitPriceAndPic.setGoods(goods);
                    }else{
                        throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
                    }
                }
            }

            List<ChannelCommodityAttribute> channelCommodityGoodsAttributeList = new ArrayList<>();
            unitPriceAndPicRequest.getAttributeAndValueList().forEach(attributeRequest -> {
                ChannelCommodityAttribute attributeAndValue = new ChannelCommodityAttribute();
                //根据配置检查属性和属性值
                Long customerAttributeId = attributeRequest.getCustomerAttribute().getId();
                if(customerAttributeId != null && customerAttributeId > 0){
                    CustomerAttribute customerAttribute = customerAttributeRepository.findById(customerAttributeId).orElse(null);
                    if(customerAttribute != null){
                        Boolean isEnable = customerAttribute.getIsEnable();
                        if(isEnable){
                            attributeAndValue.setCustomerAttribute(customerAttribute);
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_ENABLE);
                        }
                    }else{
                        throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_EXIST);
                    }
                }else{
                    throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_EXIST);
                }
                Long customerAttributeValueId = attributeRequest.getCustomerAttributeValue().getId();
                if(customerAttributeValueId != null){
                    CustomerAttributeValue customerAttributeValue = customerAttributeValueRepository.findById(customerAttributeValueId).orElse(null);
                    if(customerAttributeValue != null){
                        Boolean isEnable = customerAttributeValue.getIsEnable();
                        if(isEnable){
                            attributeAndValue.setCustomerAttributeValue(customerAttributeValue);
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_ENABLE);
                        }
                    }else{
                        throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_EXIST);
                    }
                }else{
                    CustomerAttributeValue customerAttributeValue = new CustomerAttributeValue();
                    customerAttributeValue.setValue(attributeRequest.getCustomerAttributeValue().getValue());
                    customerAttributeValue.setMemberId(sysUser.getMemberId());
                    customerAttributeValue.setMemberName(sysUser.getCompany());
                    customerAttributeValue.setUserId(sysUser.getUserId());
                    customerAttributeValue.setUserName(sysUser.getUserName());
                    attributeAndValue.setCustomerAttributeValue(customerAttributeValue);
                }
                attributeAndValue.setChannelCommodityUnitPricePic(commodityUnitPriceAndPic);
                channelCommodityGoodsAttributeList.add(attributeAndValue);
            });
            commodityUnitPriceAndPic.setAttributeAndValueList(channelCommodityGoodsAttributeList);
            commodityUnitPriceAndPic.setUnitPrice(unitPriceAndPicRequest.getUnitPrice());
            commodityUnitPriceAndPic.setChannelCommodityMember(commodityMember);
            commodityUnitPriceAndPic.setCommodityUnitPriceAndPicId(unitPriceAndPicRequest.getCommodityUnitPriceAndPicId());
            commodityUnitPriceAndPic.setId(unitPriceAndPicRequest.getId());
            commodityUnitPriceAndPicList.add(commodityUnitPriceAndPic);
        });
        return commodityUnitPriceAndPicList;
    }

    /**
     * 修改渠道商品价格
     * @param sysUser
     * @param channelCommodityUpdateRequest
     * @return
     */
    @Transactional
    @Override
    public Long updatePriceChannelCommodity(UserLoginCacheDTO sysUser, ChannelCommodityUpdateRequest channelCommodityUpdateRequest) {
        Long id = channelCommodityUpdateRequest.getId();
        ChannelCommodityMember channelCommodityMember = channelCommodityMemberRepository.findById(id).orElse(null);
        if(channelCommodityMember != null){
            List<ChannelUnitPriceAndPicRequest> unitPriceAndPicList = channelCommodityUpdateRequest.getUnitPriceAndPicList();

            //清除中间表数据
            List<Long> unitPriceAndPicRequestIdList = unitPriceAndPicList.stream().filter(unitPriceAndPicRequest -> unitPriceAndPicRequest.getId() != null).map(ChannelUnitPriceAndPicRequest::getId).collect(Collectors.toList());
            channelCommodityAttributeRepository.deleteByChannelCommodityUnitPricePicIdIn(unitPriceAndPicRequestIdList);

            List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = this.getPrice(sysUser, unitPriceAndPicList, channelCommodityMember);
            channelCommodityMember.setUnitPriceAndPicList(commodityUnitPriceAndPicList);
            //计算商品的最大值和最小值
            Double min = 0d;
            Double max = 0d;
            List<Map<String, Double>> collect = unitPriceAndPicList.stream().filter(commodityUnitPriceAndPic -> commodityUnitPriceAndPic != null && commodityUnitPriceAndPic.getUnitPrice() != null && commodityUnitPriceAndPic.getUnitPrice().size() > 0).map(ChannelUnitPriceAndPicRequest::getUnitPrice).collect(Collectors.toList());
            if(!collect.isEmpty()){
                min = Collections.min(collect.stream().map(m -> Collections.min(m.values())).collect(Collectors.toList()));
                max = Collections.max(collect.stream().map(m -> Collections.max(m.values())).collect(Collectors.toList()));
            }
            channelCommodityMember.setMin(min);
            channelCommodityMember.setMax(max);
            channelCommodityMember.setLogistics(channelCommodityUpdateRequest.getLogistics());
            channelCommodityMember.setIsMemberPrice(channelCommodityUpdateRequest.getIsMemberPrice());
            channelCommodityMemberRepository.saveAndFlush(channelCommodityMember);
            return channelCommodityMember.getId();
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_NOT_EXIST);
        }
    }

    /**
     * 批量删除商品
     * @param idList
     * @return
     */
    @Transactional
    @Override
    public String deleteBatchChannelCommodity(UserLoginCacheDTO sysUser, List<Long> idList) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        //判断渠道商品是否都存在
        List<ChannelCommodityMember> channelCommodityMemberList = channelCommodityMemberRepository.findAllByChannelCommodityMemberIdAndIdIn(memberId, idList);
        if(channelCommodityMemberList.isEmpty() || channelCommodityMemberList.size() != idList.size()){
            throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_NOT_EXIST);
        }
        //判断渠道商品是否都是未上架
        List<ChannelCommodityMember> list = channelCommodityMemberList.stream().filter(channelCommodityMember ->  CommodityStatusEnum.NEVER_Shelf.getCode().equals(channelCommodityMember.getStatus())).collect(Collectors.toList());
        if(list.isEmpty() || list.size() != idList.size()){
            throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_STATUS_DELETE);
        }
        channelCommodityMemberRepository.deleteAll(channelCommodityMemberList);

        //删除所有没有下级渠道的渠道商品
        List<Long> channelCommodityIdList = channelCommodityMemberList.stream().map(channelCommodityMember -> channelCommodityMember.getChannelCommodity().getId()).collect(Collectors.toList());
        List<ChannelCommodity> channelCommodityList = channelCommodityRepository.findByMemberIdAndMemberRoleIdAndIdInAndMemberListIsNull(memberId, memberRoleId, channelCommodityIdList);
        channelCommodityRepository.deleteAll(channelCommodityList);

        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 删除渠道商品价格--未上架的状态
     * @return
     */
    @Override
    public String deleteChannelCommodityPrice(SimpleIdRequest simpleIdRequest) {
        Long id = simpleIdRequest.getId();
        if(id != null && id > 0){
            ChannelCommodityUnitPricePic commodityUnitPriceAndPic = channelCommodityUnitPriceAndPicRepository.findById(id).orElse(null);
            if(commodityUnitPriceAndPic != null){
                Integer status = commodityUnitPriceAndPic.getChannelCommodityMember().getStatus();
                if(!CommodityStatusEnum.NEVER_Shelf.getCode().equals(status)){
                    throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_STATUS_DELETE);
                }
                channelCommodityUnitPriceAndPicRepository.delete(commodityUnitPriceAndPic);
                return ResponseCode.SUCCESS.getMessage();
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_PRICE_NOT_NULL);
    }

    /**
     * 渠道商品(单个上架/下架)
     * @param channelCommodityShopRequest
     * @return
     */
    @Transactional
    @Override
    public String publishCommodity(UserLoginCacheDTO sysUser, ChannelCommodityShopRequest channelCommodityShopRequest) {
        Long id = channelCommodityShopRequest.getId();
        Long storeId = channelCommodityShopRequest.getStoreId();
        List<ShopRequest> shopList = channelCommodityShopRequest.getShopList();
        //验证数据库中是否存在该商品
        ChannelCommodityMember channelCommodityMember = channelCommodityMemberRepository.findById(id).orElse(null);
        if(channelCommodityMember != null){
            ChannelCommodity channelCommodity = channelCommodityMember.getChannelCommodity();
            Long channelCommodityMemberId = channelCommodity.getMemberId();
            Long commodityId = channelCommodity.getCommodity().getId();
            Long channelCommodityMemberMemberId = channelCommodityMember.getMemberId();
            Long memberRoleId = channelCommodityMember.getMemberRoleId();
            //商品环境
            List<Long> shopIdList = shopList.stream().map(ShopRequest::getShopId).collect(Collectors.toList());

            //删除商品上架商城表
            channelCommodityShopRepository.deleteChannelCommodityShopByChannelCommodityMemberId(channelCommodityMember.getId());

            //上架商品的时候需要校验：发布所有渠道和发布单个渠道不能重复
            List<Long> memberIdList = new ArrayList<>();
            if(channelCommodityMemberMemberId != null && channelCommodityMemberMemberId > 0){
                //发布给某个渠道
                memberIdList.add(channelCommodityMemberMemberId);
            }else{
                //发布给所有下级渠道
                List<MemberAndRoleIdDTO> subChannelMembers = sysUser.getSubChannelMembers();
                if(subChannelMembers != null && !subChannelMembers.isEmpty()){
                    memberIdList = subChannelMembers.stream().filter(memberAndRoleIdDTO -> memberAndRoleIdDTO.getRoleId().equals(memberRoleId)).map(MemberAndRoleIdDTO::getMemberId).collect(Collectors.toList());
                }
            }
            //排除所有渠道
            memberIdList.add(0L);
            Boolean exists = channelCommodityMemberRepository.existsByShopListShopIdInAndStatusAndChannelCommodityCommodityIdAndChannelCommodityMemberIdAndMemberIdInAndMemberRoleId(shopIdList, CommodityStatusEnum.On_Shelf.getCode(), commodityId, channelCommodityMemberId, memberIdList, memberRoleId);
//            Boolean exists = channelCommodityMemberRepository.existsByMemberIdInAndStatusAndChannelCommodityCommodityIdAndShopListShopIdInAndIdIsNotAndMemberRoleId(memberIdList, CommodityStatusEnum.On_Shelf.getCode(), commodityId, shopIdList, channelCommodityMemberId, memberRoleId);
            if(exists){
                throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_PUBLISH_EXIST);
            }

            //生成商品上架商城数据
            List<ChannelCommodityShop> channelCommodityShopList = new ArrayList<>();
            shopList.forEach(shop -> {
                ChannelCommodityShop channelCommodityShop = new ChannelCommodityShop();
                channelCommodityShop.setShopId(shop.getShopId());
                channelCommodityShop.setType(shop.getType());
                channelCommodityShop.setEnvironment(shop.getEnvironment());
                channelCommodityShop.setChannelCommodityMember(channelCommodityMember);
                channelCommodityShopList.add(channelCommodityShop);
            });
            channelCommodityMember.setShopList(channelCommodityShopList);

            //商品状态
            Integer new_status;
            if(channelCommodityShopList.size() > 0){
                new_status = CommodityStatusEnum.On_Shelf.getCode();
                channelCommodityMember.setPublishTime(System.currentTimeMillis());
            }else{
                new_status = CommodityStatusEnum.Off_Shelf.getCode();
            }
            channelCommodityMember.setStatus(new_status);
            channelCommodityMember.setStoreId(storeId);
            channelCommodityMemberRepository.saveAndFlush(channelCommodityMember);
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_NOT_EXIST);
        }
        //同步es数据
        List<ChannelCommodityESResponse> channelCommodityList = new ArrayList<>();
        ChannelCommodityESResponse channelCommodityESResponse = new ChannelCommodityESResponse();
        BeanUtil.copyProperties(channelCommodityMember.getChannelCommodity(), channelCommodityESResponse);
        channelCommodityList.add(channelCommodityESResponse);
        Boolean flag = syncEsCommodityService.publishChannelCommodity(channelCommodityList);
        if(flag != null && flag){
            return ResponseCode.SUCCESS.getMessage();
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PUBLISH_FAIL);
        }
    }

    /**
     * 批量上架渠道商品
     * @param channelCommodityShopListRequest
     * @return
     */
    @Override
    public String batchPublishCommodity(UserLoginCacheDTO sysUser, ChannelCommodityShopListRequest channelCommodityShopListRequest) {
        List<ChannelCommodityMember> channelCommodityMemberList = new ArrayList<>();
        List<ChannelCommodityShop> list = new ArrayList<>();
        HashMap<Long, ChannelCommodity> channelCommodityMap = new HashMap<>();
        Long storeId = channelCommodityShopListRequest.getStoreId();
        List<Long> idList = channelCommodityShopListRequest.getIdList();
        List<ShopRequest> shopList = channelCommodityShopListRequest.getShopList();
        idList.forEach(id -> {
            //验证数据库中是否存在该商品
            ChannelCommodityMember channelCommodityMember = channelCommodityMemberRepository.findById(id).orElse(null);
            if(channelCommodityMember != null){
                ChannelCommodity channelCommodity = channelCommodityMember.getChannelCommodity();
                Long channelCommodityMemberId = channelCommodity.getMemberId();
                Long commodityId = channelCommodity.getCommodity().getId();
                Long channelCommodityId = channelCommodity.getId();
                Long channelCommodityMemberMemberId = channelCommodityMember.getMemberId();
                Long memberRoleId = channelCommodityMember.getMemberRoleId();
                //商品环境
                List<Long> shopIdList = shopList.stream().map(ShopRequest::getShopId).collect(Collectors.toList());

                //上架商品的时候需要校验：发布所有渠道和发布单个渠道不能重复
                List<Long> memberIdList = new ArrayList<>();
                if(channelCommodityMemberMemberId != null && channelCommodityMemberMemberId > 0){
                    //发布给某个渠道
                    memberIdList.add(channelCommodityMemberMemberId);
                }else{
                    //发布给所有下级渠道
                    List<MemberAndRoleIdDTO> subChannelMembers = sysUser.getSubChannelMembers();
                    if(subChannelMembers != null && !subChannelMembers.isEmpty()){
                        memberIdList = subChannelMembers.stream().filter(memberAndRoleIdDTO -> memberAndRoleIdDTO.getRoleId().equals(memberRoleId)).map(MemberAndRoleIdDTO::getMemberId).collect(Collectors.toList());
                    }
                }
                //排除所有渠道
                memberIdList.add(0L);
//                Boolean exists = channelCommodityMemberRepository.existsByMemberIdInAndStatusAndChannelCommodityCommodityIdAndShopListShopIdInAndIdIsNotAndMemberRoleId(memberIdList, CommodityStatusEnum.On_Shelf.getCode(), commodityId, shopIdList, channelCommodityMemberId, memberRoleId);
                Boolean exists = channelCommodityMemberRepository.existsByShopListShopIdInAndStatusAndChannelCommodityCommodityIdAndChannelCommodityMemberIdAndMemberIdInAndMemberRoleId(shopIdList, CommodityStatusEnum.On_Shelf.getCode(), commodityId, channelCommodityMemberId, memberIdList, memberRoleId);
                if(exists){
                    throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_PUBLISH_EXIST);
                }

                //生成商品上架商城数据
                List<ChannelCommodityShop> channelCommodityShopList = channelCommodityMember.getShopList();
                if(channelCommodityShopList != null && !channelCommodityShopList.isEmpty()){
                    List<Long> existShopIdList = channelCommodityShopList.stream().map(ChannelCommodityShop::getShopId).collect(Collectors.toList());

                    shopList.forEach(shop -> {
                        if(!existShopIdList.contains(shop.getShopId())){
                            ChannelCommodityShop channelCommodityShop = new ChannelCommodityShop();
                            channelCommodityShop.setShopId(shop.getShopId());
                            channelCommodityShop.setType(shop.getType());
                            channelCommodityShop.setEnvironment(shop.getEnvironment());
                            channelCommodityShop.setChannelCommodityMember(channelCommodityMember);
                            list.add(channelCommodityShop);
                        }
                    });
                }else{
                    shopList.forEach(shop -> {
                        ChannelCommodityShop channelCommodityShop = new ChannelCommodityShop();
                        channelCommodityShop.setShopId(shop.getShopId());
                        channelCommodityShop.setType(shop.getType());
                        channelCommodityShop.setEnvironment(shop.getEnvironment());
                        channelCommodityShop.setChannelCommodityMember(channelCommodityMember);
                        list.add(channelCommodityShop);
                    });

                    channelCommodityShopList = new ArrayList<>();
                }

                channelCommodityShopList.addAll(list);
                channelCommodityMember.setShopList(channelCommodityShopList);

                //商品状态
                Integer new_status;
                if(channelCommodityShopList.size() > 0){
                    new_status = CommodityStatusEnum.On_Shelf.getCode();
                    channelCommodityMember.setPublishTime(System.currentTimeMillis());
                }else{
                    new_status = CommodityStatusEnum.Off_Shelf.getCode();
                }
                channelCommodityMember.setStatus(new_status);
                channelCommodityMember.setStoreId(storeId);
                channelCommodityMemberList.add(channelCommodityMember);

                ChannelCommodity existChannelCommodity = channelCommodityMap.get(channelCommodityId);
                if(existChannelCommodity != null){
                    List<ChannelCommodityMember> memberList = existChannelCommodity.getMemberList();
                    memberList.add(channelCommodityMember);
                }
                channelCommodityMap.put(channelCommodityId, channelCommodity);
            }else{
                throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_NOT_EXIST);
            }
        });

        if(!channelCommodityMemberList.isEmpty()){
            channelCommodityMemberRepository.saveAll(channelCommodityMemberList);
        }

        if(channelCommodityMap.size() > 0){
            //同步搜索服务
            List<ChannelCommodityESResponse> channelCommodityList = new ArrayList<>();
            for (Map.Entry<Long, ChannelCommodity> entry : channelCommodityMap.entrySet()) {
                ChannelCommodityESResponse channelCommodityESResponse = new ChannelCommodityESResponse();
                BeanUtil.copyProperties(entry.getValue(), channelCommodityESResponse);
                channelCommodityList.add(channelCommodityESResponse);
            }
            Boolean flag = syncEsCommodityService.publishChannelCommodity(channelCommodityList);
            if(flag != null && flag){
                return ResponseCode.SUCCESS.getMessage();
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PUBLISH_FAIL);
    }

    /**
     * 批量下架渠道商品
     * @param channelCommodityShopListRequest
     * @return
     */
    @Transactional
    @Override
    public String batchOffPublishCommodity(UserLoginCacheDTO sysUser, ChannelCommodityShopListRequest channelCommodityShopListRequest) {
        List<ChannelCommodityMember> channelCommodityMemberList = new ArrayList<>();
        List<ChannelCommodityShop> list = new ArrayList<>();
        HashMap<Long, ChannelCommodity> channelCommodityMap = new HashMap<>();
        List<Long> idList = channelCommodityShopListRequest.getIdList();
        List<ShopRequest> shopList = channelCommodityShopListRequest.getShopList();
        idList.forEach(id -> {
            //验证数据库中是否存在该商品
            ChannelCommodityMember channelCommodityMember = channelCommodityMemberRepository.findById(id).orElse(null);
            if(channelCommodityMember != null){
                //生成商品上架商城数据
                List<ChannelCommodityShop> channelCommodityShopList = channelCommodityMember.getShopList();
                if(channelCommodityShopList != null && !channelCommodityShopList.isEmpty()){
                    channelCommodityShopList.forEach(channelCommodityShop -> {
                        Long shopId = channelCommodityShop.getShopId();
                        shopList.forEach(shop -> {
                            if(shopId.longValue() == shop.getShopId().longValue()){
                                list.add(channelCommodityShop);
                            }
                        });
                    });
                    channelCommodityShopList.removeAll(list);
                }

                channelCommodityMember.setShopList(channelCommodityShopList);
                //商品状态
                Integer new_status;
                if(channelCommodityShopList != null && channelCommodityShopList.size() > 0){
                    new_status = CommodityStatusEnum.On_Shelf.getCode();
                }else{
                    new_status = CommodityStatusEnum.Off_Shelf.getCode();
                }
                ChannelCommodity channelCommodity = channelCommodityMember.getChannelCommodity();
                channelCommodityMember.setStatus(new_status);
                channelCommodityMemberList.add(channelCommodityMember);

                Long channelCommodityId = channelCommodity.getId();
                ChannelCommodity existChannelCommodity = channelCommodityMap.get(channelCommodityId);
                if(existChannelCommodity != null){
                    List<ChannelCommodityMember> memberList = existChannelCommodity.getMemberList();
                    memberList.add(channelCommodityMember);
                }
                channelCommodityMap.put(channelCommodityId, channelCommodity);
            }else{
                throw new BusinessException(ResponseCode.PRODUCT_CHANNEL_COMMODITY_NOT_EXIST);
            }
        });

        //清除数据
        if(!list.isEmpty()){
            channelCommodityShopRepository.deleteAll(list);
        }

        if(!channelCommodityMemberList.isEmpty()){
            channelCommodityMemberRepository.saveAll(channelCommodityMemberList);
        }

        if(channelCommodityMap.size() > 0){
            //同步搜索服务
            List<ChannelCommodityESResponse> channelCommodityList = new ArrayList<>();
            for (Map.Entry<Long, ChannelCommodity> entry : channelCommodityMap.entrySet()) {
                ChannelCommodityESResponse channelCommodityESResponse = new ChannelCommodityESResponse();
                BeanUtil.copyProperties(entry.getValue(), channelCommodityESResponse);
                channelCommodityList.add(channelCommodityESResponse);
            }
            Boolean flag = syncEsCommodityService.publishChannelCommodity(channelCommodityList);
            if(flag != null && flag){
                return ResponseCode.SUCCESS.getMessage();
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PUBLISH_FAIL);
    }

    /**
     * 下架某个渠道会员的所有商品
     * @return
     */
    @Transactional
    @Override
    public Boolean offPublishAllCommodity(Long memberId, Long memberRoleId) {
        List<Long> channelCommodityMemberIdList = new ArrayList<>();
        //查询会员的所有商品
        List<ChannelCommodity> list = channelCommodityRepository.findByMemberIdAndMemberRoleId(memberId, memberRoleId);
        List<ChannelCommodity> channelCommodityList = list.stream().peek(channelCommodity -> {
            List<ChannelCommodityMember> memberList = channelCommodity.getMemberList();
            memberList.forEach(channelCommodityMember -> {
                Integer status = channelCommodityMember.getStatus();
                if(CommodityStatusEnum.On_Shelf.getCode().equals(status)){
                    channelCommodityMemberIdList.add(channelCommodityMember.getId());
                    channelCommodityMember.setShopList(null);
                    channelCommodityMember.setStatus(CommodityStatusEnum.Off_Shelf.getCode());
                }
            });
        }).collect(Collectors.toList());

        if(!channelCommodityMemberIdList.isEmpty()){
            //删除商品上架商城表
            channelCommodityShopRepository.deleteChannelCommodityShopByChannelCommodityMemberIdIn(channelCommodityMemberIdList);
            channelCommodityRepository.saveAll(channelCommodityList);

            //同步ES数据
            syncEsCommodityService.offPublishAllChannelCommodity(channelCommodityMemberIdList);
        }
        return true;
    }

    /**
     * 查询商品列表(按具体商品查询)
     * @param pageVO 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @return
     */
    @Override
    public PageData<CommodityGoodsResponse> getCommodityDetailList(PageVO pageVO, CommodityDetailRequest commodityDetailRequest, Long loginMemberId) {
        List<Long> shopIdList = commodityDetailRequest.getShopIdList();
        List<CommodityGoodsResponse> commodityGoodsResponseList = new ArrayList<>();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<ChannelCommodityUnitPricePic> list = channelCommodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest), page);
        List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = list.getContent();
        if(!commodityUnitPriceAndPicList.isEmpty()){
            List<Object> resultList = null;
            if(shopIdList != null && shopIdList.size() > 0){
                //组装redis键值格式
                List<HashMap<String, String[]>> keyFieldList = commodityUnitPriceAndPicList.stream().map(unitPriceAndPic -> {
                    HashMap<String, String[]> map = new HashMap<>();
                    String unitPriceAndPicId = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopIdList.get(0) + "_" + unitPriceAndPic.getCommodityUnitPriceAndPicId();
                    //渠道商品要取childMemberId
                    String commodityMemberId = String.valueOf(loginMemberId);
                    map.put(unitPriceAndPicId, new String[]{commodityMemberId, CommonConstant.FREIGHT_All});
                    return map;
                }).collect(Collectors.toList());

                //获取库存数据并赋值
                resultList = redisStringUtils.hMGetBatch(keyFieldList, Constants.REDIS_PRODUCT_INDEX);
            }

            for(int i = 0; i < commodityUnitPriceAndPicList.size(); i++){
                ChannelCommodityUnitPricePic commodityUnitPriceAndPic = commodityUnitPriceAndPicList.get(i);
                ChannelCommodityMember channelCommodityMember = commodityUnitPriceAndPic.getChannelCommodityMember();
                ChannelCommodity channelCommodity = channelCommodityMember.getChannelCommodity();
                Commodity commodity = channelCommodity.getCommodity();

                CommodityGoodsResponse commodityGoodsResponse = new CommodityGoodsResponse();
                commodityGoodsResponse.setIsChannelCommodity(true);
                commodityGoodsResponse.setCommodityId(channelCommodityMember.getId());
                commodityGoodsResponse.setId(commodityUnitPriceAndPic.getId());
                if(commodityUnitPriceAndPic.getGoods() != null){
                    commodityGoodsResponse.setGoodsId(commodityUnitPriceAndPic.getGoods().getId());
                }
                //商品价格
                Map<String, Double> unitPrice = commodityUnitPriceAndPic.getUnitPrice();
                if(unitPrice != null && unitPrice.size() > 0){
                    commodityGoodsResponse.setMin(Collections.min(unitPrice.values()));
                    commodityGoodsResponse.setMax(Collections.max(unitPrice.values()));
                    commodityGoodsResponse.setUnitPrice(unitPrice);
                }

                //商品属性
                List<ChannelCommodityAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().map(channelCommodityAttribute -> channelCommodityAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if(StringUtils.isNotEmpty(attribute)){
                    commodityGoodsResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
                }else{
                    commodityGoodsResponse.setName(commodity.getName());
                }
                commodityGoodsResponse.setCode(commodity.getCode());
                commodityGoodsResponse.setUnitName(commodity.getUnitName());
                commodityGoodsResponse.setPriceType(commodity.getPriceType());
                commodityGoodsResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                if(commodity.getBrand() != null){
                    commodityGoodsResponse.setBrandName(commodity.getBrand().getName());
                }
                commodityGoodsResponse.setApplyTime(commodity.getApplyTime());
                commodityGoodsResponse.setIsMemberPrice(commodity.getIsMemberPrice());
                commodityGoodsResponse.setStatus(channelCommodityMember.getStatus());
                commodityGoodsResponse.setMemberId(channelCommodityMember.getChannelCommodity().getMemberId());
                commodityGoodsResponse.setMemberName(channelCommodityMember.getChannelCommodity().getMemberName());
                commodityGoodsResponse.setMemberRoleId(channelCommodityMember.getChannelCommodity().getMemberRoleId());
                commodityGoodsResponse.setMemberRoleName(channelCommodityMember.getChannelCommodity().getMemberRoleName());
                commodityGoodsResponse.setMainPic(commodity.getMainPic());
                commodityGoodsResponse.setMinOrder(commodity.getMinOrder());
                commodityGoodsResponse.setTaxRate(commodity.getTaxRate());
                commodityGoodsResponse.setCommodityUnitPriceAndPicId(commodityUnitPriceAndPic.getCommodityUnitPriceAndPicId());
                LogisticsRequest logistics = channelCommodityMember.getLogistics();
                if(logistics != null){
                    commodityGoodsResponse.setLogistics(BeanUtil.copyProperties(logistics, LogisticsResponse.class));
                }

                //计算当前商品的库存数
                if(resultList != null && resultList.size() > 0){
                    List<String> stockList = (List<String>)resultList.get(i);
                    if(stockList != null && !stockList.isEmpty()){
                        List<String> collect = stockList.stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
                        if(!collect.isEmpty()){
                            Double stockCount = collect.stream().map(Double::parseDouble).reduce(Double::sum).get();
                            commodityGoodsResponse.setStockCount(stockCount);
                        }
                    }
                }
                commodityGoodsResponseList.add(commodityGoodsResponse);
            }
        }
        return new PageData<>(list.getTotalElements(), commodityGoodsResponseList);
    }

    /**
     * 查询商品列表(按会员商品规格查询)
     * @param pageVO 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @return
     */
    @Override
    public PageData<CommodityStockResponse> getCommodityDetailStockList(PageVO pageVO, CommodityDetailRequest commodityDetailRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<ChannelCommodityUnitPricePic> list = channelCommodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest), page);
        List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = list.getContent();
        List<Long> commodityUnitPriceAndPicIdList = new ArrayList<>();
        List<CommodityStockResponse> commodityStockResponseList = commodityUnitPriceAndPicList.stream().map(channelCommodityUnitPricePic -> {
            Long commodityUnitPriceAndPicId = channelCommodityUnitPricePic.getCommodityUnitPriceAndPicId();
            if(commodityUnitPriceAndPicIdList.contains(commodityUnitPriceAndPicId)){
                return null;
            }else{
                commodityUnitPriceAndPicIdList.add(commodityUnitPriceAndPicId);
            }
            //商品信息
            Commodity commodity = channelCommodityUnitPricePic.getChannelCommodityMember().getChannelCommodity().getCommodity();
            Long commodityId = commodity.getId();
            String code = commodity.getCode();
            String customerCategoryName = commodity.getCustomerCategory().getName();
            String unitName = commodity.getUnitName();
            CommodityStockResponse commodityStockResponse = new CommodityStockResponse();
            commodityStockResponse.setId(commodityUnitPriceAndPicId);

            //商品属性
            List<ChannelCommodityAttribute> attributeAndValueList = channelCommodityUnitPricePic.getAttributeAndValueList();
            String attribute = StringUtils.join(attributeAndValueList.stream().map(channelCommodityAttribute -> channelCommodityAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
            if(StringUtils.isNotEmpty(attribute)){
                commodityStockResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
            }else{
                commodityStockResponse.setName(commodity.getName());
            }
            commodityStockResponse.setCode(code);
            if(commodity.getBrand() != null){
                commodityStockResponse.setBrandName(commodity.getBrand().getName());
            }
            if(channelCommodityUnitPricePic.getGoods() != null){
                commodityStockResponse.setGoodsId(channelCommodityUnitPricePic.getGoods().getId());
                commodityStockResponse.setGoodsCode(channelCommodityUnitPricePic.getGoods().getCode());
                commodityStockResponse.setGoodsName(channelCommodityUnitPricePic.getGoods().getName());
            }
            commodityStockResponse.setCommodityId(commodityId);
            commodityStockResponse.setCustomerCategoryName(customerCategoryName);
            commodityStockResponse.setUnitName(unitName);

            List<ChannelCommodityMember> memberList = channelCommodityUnitPricePic.getChannelCommodityMember().getChannelCommodity().getMemberList();
            List<CommodityMemberResponse> commodityMemberResponseList = memberList.stream().map(channelCommodityMember -> {
                CommodityMemberResponse commodityMemberResponse = new CommodityMemberResponse();
                commodityMemberResponse.setMemberId(channelCommodityMember.getMemberId());
                commodityMemberResponse.setRoleId(channelCommodityMember.getMemberRoleId());
                return commodityMemberResponse;
            }).collect(Collectors.toList());

            commodityStockResponse.setMembers(commodityMemberResponseList);
            return commodityStockResponse;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        return new PageData<>(list.getTotalElements(), commodityStockResponseList);
    }

    /**
     * 查询所有渠道商品对应的商品id
     * @param memberId
     * @return
     */
    @Override
    public List<Long> findCommodityIdByMember(Long memberId, Long memberRoleId) {
        List<ChannelCommodity> channelCommodityList = channelCommodityRepository.findByMemberIdAndMemberRoleId(memberId, memberRoleId);
        if(channelCommodityList != null && !channelCommodityList.isEmpty()){
            return channelCommodityList.stream().map(channelCommodity -> channelCommodity.getCommodity().getId()).collect(Collectors.toList());
        }else{
            return null;
        }
    }

    /**
     * 查询商品sku列表
     * @param pageVO 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @return
     */
    @Override
    public PageData<CommoditySkuResponse> getChannelCommoditySkuListByShopId(PageVO pageVO, CommodityDetailRequest commodityDetailRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<ChannelCommodityUnitPricePic> list = channelCommodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest), page);
        List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = list.getContent();
        List<Long> commodityUnitPriceAndPicIdList = new ArrayList<>();
        List<CommoditySkuResponse> commodityStockResponseList = commodityUnitPriceAndPicList.stream().map(channelCommodityUnitPricePic -> {
            Long commodityUnitPriceAndPicId = channelCommodityUnitPricePic.getCommodityUnitPriceAndPicId();
            if(commodityUnitPriceAndPicIdList.contains(commodityUnitPriceAndPicId)){
                return null;
            }else{
                commodityUnitPriceAndPicIdList.add(commodityUnitPriceAndPicId);
            }
            //商品信息
            Commodity commodity = channelCommodityUnitPricePic.getChannelCommodityMember().getChannelCommodity().getCommodity();
            Long commodityId = commodity.getId();
            String code = commodity.getCode();
            String customerCategoryName = commodity.getCustomerCategory().getName();
            String unitName = commodity.getUnitName();
            String mainPic = commodity.getMainPic();
            Double minOrder = commodity.getMinOrder();
            Integer priceType = commodity.getPriceType();

            CommoditySkuResponse commoditySkuResponse = new CommoditySkuResponse();
            commoditySkuResponse.setId(commodityUnitPriceAndPicId);

            //商品价格
            commoditySkuResponse.setUnitPrice(channelCommodityUnitPricePic.getUnitPrice());
            //物流信息
            LogisticsRequest logistics = channelCommodityUnitPricePic.getChannelCommodityMember().getLogistics();
            commoditySkuResponse.setLogistics(BeanUtil.copyProperties(logistics, LogisticsResponse.class));

            //商品属性
            List<ChannelCommodityAttribute> attributeAndValueList = channelCommodityUnitPricePic.getAttributeAndValueList();
            String attribute = StringUtils.join(attributeAndValueList.stream().map(channelCommodityAttribute -> channelCommodityAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
            if(StringUtils.isNotEmpty(attribute)){
                commoditySkuResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
            }else{
                commoditySkuResponse.setName(commodity.getName());
            }
            commoditySkuResponse.setCode(code);
            if(commodity.getBrand() != null){
                commoditySkuResponse.setBrandName(commodity.getBrand().getName());
            }
            commoditySkuResponse.setCommodityId(commodityId);
            commoditySkuResponse.setCustomerCategoryName(customerCategoryName);
            commoditySkuResponse.setUnitName(unitName);
            commoditySkuResponse.setMainPic(mainPic);
            commoditySkuResponse.setMinOrder(minOrder);
            commoditySkuResponse.setPriceType(priceType);

            return commoditySkuResponse;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        return new PageData<>(list.getTotalElements(), commodityStockResponseList);
    }

    /**
     * 判断商品是否上架
     * @return
     */
    @Override
    public String getCommodityIsPublish(Long shopId, List<CommodityNameRequest> commodityNameList) {
        List<Long> commodityIdList = commodityNameList.stream().map(CommodityNameRequest::getCommodityId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        List<ChannelCommodityShop> channelCommodityShopList = channelCommodityShopRepository.findByChannelCommodityMemberIdInAndShopId(commodityIdList, shopId);
        //判断是否存在未上架的商品
        if(commodityIdList.size() != channelCommodityShopList.size()){
            List<Long> onLineChannelProductIdList = channelCommodityShopList.stream().map(item -> item.getChannelCommodityMember().getChannelCommodity().getId()).collect(Collectors.toList());
            List<Long> offLineChannelProductIdList = commodityIdList.stream().filter(item -> !onLineChannelProductIdList.contains(item)).collect(Collectors.toList());
            if(offLineChannelProductIdList.size() > 0){
                //获取未上架的所有商品名称，通过逗号隔开
                String commodityName = commodityNameList.stream().filter(item -> offLineChannelProductIdList.contains(item.getCommodityId())).map(CommodityNameRequest::getCommodityName).collect(Collectors.joining(","));
                return "渠道商品：" + commodityName + " 已下架";
            }
        }
        return null;
    }

    /**
     * 判断商品是否上架
     * @return
     */
    @Override
    public List<Long> getCommodityListByIsPublish(Long shopId, List<CommodityNameRequest> commodityNameList) {
        List<Long> commodityIdList = commodityNameList.stream().map(CommodityNameRequest::getCommodityId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        List<ChannelCommodityShop> channelCommodityShopList = channelCommodityShopRepository.findByChannelCommodityMemberIdInAndShopId(commodityIdList, shopId);
        //判断是否存在未上架的商品
        if(commodityIdList.size() != channelCommodityShopList.size()){
            return channelCommodityShopList.stream().map(item -> item.getChannelCommodityMember().getChannelCommodity().getId()).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 查询商品信息列表--订单校验商品信息
     * @param commodityPriceRequest 查询条件实体
     * @return
     */
    @Override
    public List<CommodityOrderResponse> getCommodityListByOrder(CommodityPriceRequest commodityPriceRequest) {
        Long shopId = commodityPriceRequest.getShopId();
        List<Long> commoditySkuIdList = commodityPriceRequest.getCommoditySkuIdList();

        List<CommodityOrderResponse> commodityOrderResponseList = new ArrayList<>();
        List<ChannelCommodityUnitPricePic> commodityUnitPriceAndPicList = channelCommodityUnitPriceAndPicRepository.findAllById(commoditySkuIdList);
        for(int i = 0; i < commodityUnitPriceAndPicList.size(); i++){
            ChannelCommodityUnitPricePic commodityUnitPriceAndPic = commodityUnitPriceAndPicList.get(i);
            ChannelCommodityMember channelCommodityMember = commodityUnitPriceAndPic.getChannelCommodityMember();
            ChannelCommodity channelCommodity = channelCommodityMember.getChannelCommodity();
            Commodity commodity = channelCommodity.getCommodity();

            CommodityOrderResponse commodityOrderResponse = new CommodityOrderResponse();
            commodityOrderResponse.setCommodityId(channelCommodity.getId());
            commodityOrderResponse.setId(commodityUnitPriceAndPic.getId());
            //商品价格
            Map<String, Double> unitPrice = commodityUnitPriceAndPic.getUnitPrice();
            if(unitPrice != null && unitPrice.size() > 0){
                commodityOrderResponse.setMin(Collections.min(unitPrice.values()));
                commodityOrderResponse.setMax(Collections.max(unitPrice.values()));
                commodityOrderResponse.setUnitPrice(unitPrice);
            }

            //商品属性
            List<ChannelCommodityAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
            String attribute = StringUtils.join(attributeAndValueList.stream().map(channelCommodityAttribute -> channelCommodityAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
            if(StringUtils.isNotEmpty(attribute)){
                commodityOrderResponse.setAttribute(attribute);
            }
            commodityOrderResponse.setName(commodity.getName());
            commodityOrderResponse.setCode(commodity.getCode());
            commodityOrderResponse.setUnitName(commodity.getUnitName());
            commodityOrderResponse.setPriceType(commodity.getPriceType());
            commodityOrderResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
            if(commodity.getBrand() != null){
                commodityOrderResponse.setBrandName(commodity.getBrand().getName());
            }
            commodityOrderResponse.setIsMemberPrice(commodity.getIsMemberPrice());
            commodityOrderResponse.setMemberId(channelCommodityMember.getChannelCommodity().getMemberId());
            commodityOrderResponse.setMemberName(channelCommodityMember.getChannelCommodity().getMemberName());
            commodityOrderResponse.setMemberRoleId(channelCommodityMember.getChannelCommodity().getMemberRoleId());
            commodityOrderResponse.setMemberRoleName(channelCommodityMember.getChannelCommodity().getMemberRoleName());
            commodityOrderResponse.setMainPic(commodity.getMainPic());
            commodityOrderResponse.setMinOrder(commodity.getMinOrder());
            commodityOrderResponse.setTaxRate(commodity.getTaxRate());
            commodityOrderResponse.setCommodityUnitPriceAndPicId(commodityUnitPriceAndPic.getCommodityUnitPriceAndPicId());
            LogisticsRequest logistics = channelCommodityMember.getLogistics();
            if(logistics != null){
                commodityOrderResponse.setLogistics(BeanUtil.copyProperties(logistics, LogisticsResponse.class));
            }

            //是否上架
            List<ChannelCommodityShop> shopList = channelCommodityMember.getShopList();
            if(shopList != null && shopList.size() > 0){
                List<Long> channelCommodityShopIdList = shopList.stream().map(ChannelCommodityShop::getShopId).collect(Collectors.toList());
                if(channelCommodityShopIdList.size() > 0 && channelCommodityShopIdList.contains(shopId)){
                    commodityOrderResponse.setIsPublish(true);
                }
            }
            commodityOrderResponseList.add(commodityOrderResponse);
        }
        return commodityOrderResponseList;
    }

    /**
     * 构建查询条件(查商品详情)
     * @param commodityDetailRequest
     * @return
     */
    private Specification<ChannelCommodityUnitPricePic> getCommodityDetailSpecification(CommodityDetailRequest commodityDetailRequest){
        return (Specification<ChannelCommodityUnitPricePic>) (root, query, criteriaBuilder) -> {
            List<Long> idNotInList = commodityDetailRequest.getIdNotInList();
            List<Long> shopIdList = commodityDetailRequest.getShopIdList();
            List<Integer> statusList = commodityDetailRequest.getStatusList();
            String name = commodityDetailRequest.getName();
            Long customerCategoryId = commodityDetailRequest.getCustomerCategoryId();
            Long categoryId = commodityDetailRequest.getCategoryId();
            Long brandId = commodityDetailRequest.getBrandId();
            List<Integer> priceTypeList = commodityDetailRequest.getPriceTypeList();
            Double max = commodityDetailRequest.getMax();
            Double min = commodityDetailRequest.getMin();
            Long memberId = commodityDetailRequest.getMemberId();
            Long memberRoleId = commodityDetailRequest.getMemberRoleId();
            Long childMemberId = commodityDetailRequest.getChildMemberId();
            Integer shopType = commodityDetailRequest.getShopType();
            Integer environment = commodityDetailRequest.getEnvironment();

            Predicate finalConditions = criteriaBuilder.conjunction();

            List<String> attributeNameList = new ArrayList<>();
            if(StringUtils.isNotEmpty(name)){
                if(name.contains(Constants.COMMODITY_NAME_SPLIT_STR)){
                    String[] split = name.split(Constants.COMMODITY_NAME_SPLIT_STR);
                    name = split[0];
                    attributeNameList = Arrays.stream(split).collect(Collectors.toList());
                    attributeNameList.remove(0);
                }
            }

            //属性值
            if(!attributeNameList.isEmpty()){
                Join join = root.join(root.getModel().getList("attributeAndValueList", ChannelCommodityAttribute.class),JoinType.LEFT);
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(join.get("customerAttributeValue").get("value")).value(attributeNameList));
            }

            //排除id
            if(idNotInList != null && !idNotInList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.not(criteriaBuilder.in(root.get("id")).value(idNotInList)));
            }

            //状态
            if(statusList != null && !statusList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("channelCommodityMember").get("status")).value(statusList));
            }

            //价格类型
            if(priceTypeList != null && !priceTypeList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("channelCommodityMember").get("channelCommodity").get("commodity").get("priceType")).value(priceTypeList));
            }

            //关键字查询(商品名称,商品编号)
            if(!StringUtils.isEmpty(name)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("channelCommodityMember").get("channelCommodity").get("commodity").get("code").as(String.class), "%" + name + "%"), criteriaBuilder.like(root.get("channelCommodityMember").get("channelCommodity").get("commodity").get("name").as(String.class), "%" + name + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //会员品类
            if(customerCategoryId != null && customerCategoryId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodityMember").get("channelCommodity").get("commodity").get("customerCategory").as(CustomerCategory.class), customerCategoryId));
            }
            //平台后台品类
            if(categoryId != null && categoryId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodityMember").get("channelCommodity").get("commodity").get("customerCategory").get("category").as(Category.class), categoryId));
            }

            //品牌
            if(brandId != null && brandId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodityMember").get("channelCommodity").get("commodity").get("brand").as(Brand.class), brandId));
            }

            //商城id
            if(shopIdList != null && shopIdList.size() > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.join("channelCommodityMember").join("shopList").get("shopId")).value(shopIdList));
            }

            //商城类型
            if(shopType != null && shopType > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.join("channelCommodityMember").join("shopList").get("type"), shopType));
            }

            //商城环境
            if(environment != null && environment > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.join("channelCommodityMember").join("shopList").get("environment"), environment));
            }

            //会员id
            if(memberId != null && memberId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodityMember").get("channelCommodity").get("memberId"), memberId));
            }

            //会员角色id
            if(memberRoleId != null && memberRoleId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodityMember").get("channelCommodity").get("memberRoleId"), memberRoleId));
            }

            //下级渠道会员id
            if(childMemberId != null && childMemberId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.or(criteriaBuilder.and(criteriaBuilder.notEqual(root.get("channelCommodityMember").get("channelCommodity").get("memberId").as(Long.class), childMemberId), criteriaBuilder.equal(root.get("channelCommodityMember").get("memberId"), 0)), criteriaBuilder.equal(root.get("channelCommodityMember").get("memberId").as(Long.class), childMemberId)));
            }

            //价格-积分
            if(min != null && min > 0 && max != null && max > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.and(criteriaBuilder.ge(root.get("channelCommodityMember").get("max"), min),criteriaBuilder.le(root.get("channelCommodityMember").get("min"), max)));
            }else{
                if(min != null && min > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("channelCommodityMember").get("max"), min));
                }
                if(max != null && max > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("channelCommodityMember").get("min"), max));
                }
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return  query.distinct(true).where(finalConditions).orderBy(idOrder).getRestriction();
        };
    }

    /**
     * 构建查询条件
     * @param channelCommodityQueryRequest
     * @return
     */
    private Specification<ChannelCommodityMember> getSpecification(ChannelCommodityQueryRequest channelCommodityQueryRequest){
        return (Specification<ChannelCommodityMember>) (root, query, criteriaBuilder) -> {
            Long productId = channelCommodityQueryRequest.getProductId();
            String name = channelCommodityQueryRequest.getName();
            List<Integer> priceTypeList = channelCommodityQueryRequest.getPriceTypeList();
            Long customerCategoryId = channelCommodityQueryRequest.getCustomerCategoryId();
            String customerCategoryName = channelCommodityQueryRequest.getCustomerCategoryName();
            Long categoryId = channelCommodityQueryRequest.getCategoryId();
            Long brandId = channelCommodityQueryRequest.getBrandId();
            String brandName = channelCommodityQueryRequest.getBrandName();
            List<Integer> statusList = channelCommodityQueryRequest.getStatusList();
            Double min = channelCommodityQueryRequest.getMin();
            Double max = channelCommodityQueryRequest.getMax();
            Integer source = channelCommodityQueryRequest.getSource();
            List<Long> memberIdList = channelCommodityQueryRequest.getMemberIdList();
            Long childMemberId = channelCommodityQueryRequest.getChildMemberId();
            Long childMemberRoleId = channelCommodityQueryRequest.getChildMemberRoleId();
            String memberName = channelCommodityQueryRequest.getMemberName();
            String memberRoleName = channelCommodityQueryRequest.getMemberRoleName();
            Long channelMemberId = channelCommodityQueryRequest.getChannelMemberId();
            Long channelMemberRoleId = channelCommodityQueryRequest.getChannelMemberRoleId();

            Predicate finalConditions = criteriaBuilder.conjunction();

            //商品id
            if(productId != null && productId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodity").get("id"), productId));
            }
            //关键字查询(商品名称,商品编号)
            if(!StringUtils.isEmpty(name)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("channelCommodity").get("commodity").get("code").as(String.class), "%" + name + "%"), criteriaBuilder.like(root.get("channelCommodity").get("commodity").get("name").as(String.class), "%" + name + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //发布渠道商品的会员id
            if(channelMemberId != null && channelMemberId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodity").get("memberId"), channelMemberId));
            }

            //发布渠道商品的会员角色id
            if(channelMemberRoleId != null && channelMemberRoleId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodity").get("memberRoleId"), channelMemberRoleId));
            }

            //渠道会员名称
            if(!StringUtils.isEmpty(memberName)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("memberName").as(String.class), "%" + memberName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //渠道会员角色名称
            if(!StringUtils.isEmpty(memberRoleName)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("memberRoleName").as(String.class), "%" + memberRoleName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //产品定价
            if(priceTypeList != null && !priceTypeList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("channelCommodity").get("commodity").get("priceType")).value(priceTypeList));
            }

            //会员品类
            if(customerCategoryId != null && customerCategoryId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodity").get("commodity").get("customerCategory").as(CustomerCategory.class), customerCategoryId));
            }
            if(!StringUtils.isEmpty(customerCategoryName)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("channelCommodity").get("commodity").get("customerCategory").get("name").as(String.class), "%" + customerCategoryName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //平台后台品类
            if(categoryId != null && categoryId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodity").get("commodity").get("customerCategory").get("category").as(Category.class), categoryId));
            }

            //品牌
            if(brandId != null && brandId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodity").get("commodity").get("brand").as(Brand.class), brandId));
            }
            if(!StringUtils.isEmpty(brandName)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("channelCommodity").get("commodity").get("brand").get("name").as(String.class), "%" + brandName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //渠道会员名称
            if(!StringUtils.isEmpty(memberName)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("memberName").as(String.class), "%" + memberName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //渠道商品会员id
            if(memberIdList != null && !memberIdList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("channelCommodity").get("memberId")).value(memberIdList));
            }

            //下级渠道会员id
            if(childMemberId != null && childMemberId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.or(criteriaBuilder.and(criteriaBuilder.notEqual(root.get("channelCommodity").get("memberId"), childMemberId), criteriaBuilder.equal(root.get("memberId"), 0)), criteriaBuilder.equal(root.get("memberId").as(Long.class), childMemberId)));
            }

            //下级渠道会员角色id
            if(childMemberRoleId != null && childMemberRoleId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId"), childMemberRoleId));
            }

            //商品来源
            if(source != null && source > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("channelCommodity").get("source").as(Integer.class), source));
            }
            //状态
            if(statusList != null && !statusList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("status")).value(statusList));
            }
            //价格-积分
            if(min != null && min > 0 && max != null && max > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.and(criteriaBuilder.ge(root.get("max"), min),criteriaBuilder.le(root.get("min"), max)));
            }else{
                if(min != null && min > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("max"), min));
                }
                if(max != null && max > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("min"), max));
                }
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("channelCommodity").get("id"));

            return  query.orderBy(idOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 构建查询条件
     * @param channelCommodityQueryRequest
     * @return
     */
    private Specification<ChannelCommodity> getChannelCommoditySpecification(ChannelCommodityQueryRequest channelCommodityQueryRequest){
        return (Specification<ChannelCommodity>) (root, query, criteriaBuilder) -> {
            String name = channelCommodityQueryRequest.getName();
            List<Integer> priceTypeList = channelCommodityQueryRequest.getPriceTypeList();
            Long customerCategoryId = channelCommodityQueryRequest.getCustomerCategoryId();
            Long categoryId = channelCommodityQueryRequest.getCategoryId();
            Long brandId = channelCommodityQueryRequest.getBrandId();
            Double min = channelCommodityQueryRequest.getMin();
            Double max = channelCommodityQueryRequest.getMax();
            Integer source = channelCommodityQueryRequest.getSource();
            List<Long> memberIdList = channelCommodityQueryRequest.getMemberIdList();
            String memberName = channelCommodityQueryRequest.getMemberName();
            String memberRoleName = channelCommodityQueryRequest.getMemberRoleName();

            Predicate finalConditions = criteriaBuilder.conjunction();
            //关键字查询(商品名称,商品编号)
            if(!StringUtils.isEmpty(name)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("commodity").get("code").as(String.class), "%" + name + "%"), criteriaBuilder.like(root.get("channelCommodity").get("name").as(String.class), "%" + name + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //渠道会员名称
            if(!StringUtils.isEmpty(memberName)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("memberName").as(String.class), "%" + memberName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //渠道会员角色名称
            if(!StringUtils.isEmpty(memberRoleName)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("memberRoleName").as(String.class), "%" + memberRoleName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //产品定价
            if(priceTypeList != null && !priceTypeList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("commodity").get("priceType")).value(priceTypeList));
            }
            //会员品类
            if(customerCategoryId != null && customerCategoryId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("customerCategory").as(CustomerCategory.class), customerCategoryId));
            }
            //平台后台品类
            if(categoryId != null && categoryId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("customerCategory").get("category").as(Category.class), categoryId));
            }
            //品牌
            if(brandId != null && brandId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("brand").as(Brand.class), brandId));
            }
            //会员id
            if(memberIdList != null && !memberIdList.isEmpty()){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("memberId")).value(memberIdList));
            }
            //商品来源
            if(source != null && source > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("source").as(Integer.class), source));
            }
            //价格-积分
            if(min != null && min > 0 && max != null && max > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.and(criteriaBuilder.ge(root.get("commodity").get("max"), min),criteriaBuilder.le(root.get("commodity").get("min"), max)));
            }else{
                if(min != null && min > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("commodity").get("max"), min));
                }
                if(max != null && max > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("commodity").get("min"), max));
                }
            }

            //排序
            Order applyTimeOrder = criteriaBuilder.desc(root.get("createTime"));
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return  query.orderBy(applyTimeOrder, idOrder).where(finalConditions).getRestriction();
        };
    }

}

